package com.qc.blogsystemplus.controller;

import com.qc.blogsystemplus.bean.ResponseBean;
import com.qc.blogsystemplus.entity.Discuss;
import com.qc.blogsystemplus.service.DiscussService;
import com.qc.blogsystemplus.util.JWTUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class DiscussController {

    @Autowired
    private DiscussService discussService;

    @GetMapping("/getdiscuss")
    public ResponseBean getDiscuss(@RequestParam("aid") int aid){
        List<Discuss> list = discussService.getDiscuss(aid);
        if (list.isEmpty()){
            list = null;
        }
        return new ResponseBean(200,"成功",list);
    }

    @RequiresRoles("user")
    @PostMapping("/adddiscuss")
    public ResponseBean addDiscuss (@RequestBody Discuss discuss) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            String username = JWTUtil.getUsername(subject.getPrincipal().toString());
            if (! username.equals(discuss.getUsername())){
                return new ResponseBean(401,"失败",null);
            }
            int re = discussService.addDiscuss(discuss);
            if (re != 0)
                return new ResponseBean(200,"评论成功",null);
            return new ResponseBean(402,"评论失败，请重试",null);
        } else {
            return new ResponseBean(402,"失败",null);
        }
    }

    @RequiresRoles("user")
    @GetMapping("/gooddiscuss")
    public ResponseBean goodDiscuss () {
        return new ResponseBean(200,"点赞成功",null);
    }
}
